package chapter12;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-03-23 下午2:10
 */
public class EchoService {
    public static void main(String[] args) {
        System.out.println("waiting for connecting...");
        try (ServerSocket server = new ServerSocket(6001);
             Socket socket = server.accept();
             Scanner input = new Scanner(socket.getInputStream());
             PrintStream output = new PrintStream(socket.getOutputStream())) {
            input.useDelimiter("\n");
            boolean flag = true;
            while (flag) {
                if (input.hasNext()) {
                    String rawMsg = input.next();
                    String receiveMsg = rawMsg.trim();
                    System.out.println("[receive from client]:" + receiveMsg);
                    if ("quit".equals(receiveMsg)) {
                        flag = false;
                        System.out.println("quiting...");
                    } else {
                        output.println(String.format("ECHO-%s", receiveMsg));
                    }
                }
            }
            System.out.println("service stop.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
